const mongoose = require('mongoose')
const { resolve } = require('path')
const db = 'mongodb://localhost/koa2-trailer-test'
const glob = require('glob')

mongoose.Promise = global.Promise

var Schema = mongoose.Schema;

exports.initSchemas = () => {
  glob.sync(resolve(__dirname, './schema', '**/*.js')).forEach(require)
}

exports.initAdmin = async () => {
  const User = mongoose.model('User')
  let user = await User.findOne({
    username: 'Loading'
  })

  if(!user){
    const user = new User({
      username: 'Loading',
      email: '604237073@qq.com',
      password: 'yytt861124'
    })
    await user.save()
  }
}

exports.connect = () => {
  let maxConnectTimes = 0;
  return new Promise((resolve, reject) => {
    if(process.env.NODE_ENV !== 'production'){
      mongoose.set('debug', true)
    }
  
    mongoose.connect(db)
  
    mongoose.connection.on('disconnect', () => {
      maxConnectTimes ++
      if(maxConnectTimes < 5){
        mongoose.connect(db)
      }else{
        throw new Error('数据库挂了吧...')
      }
    })
  
    mongoose.connection.on('error', err => {
      maxConnectTimes ++
      if(maxConnectTimes < 5){
        mongoose.connect(db)
      }else{
        throw new Error('数据库挂了吧...')
      }
    })
  
    mongoose.connection.once('open', () => {
      resolve()
      console.log('Mongodb Connected Successful!')

      // var blogSchema = new Schema({
      //   name:  String,
      //   age: String
      // });

      // var Blog = mongoose.model('Blog', blogSchema);

      // const blog = new Blog({
      //   "name": "loading",
      //   "age" : 30
      // })

      // blog.save().then(() => {
      //   console.log('数据保存成功！')
      // })
    })
  })
  
}